<template>
	<div>
		<use-table ref="tbl"></use-table>
		<div class="container padding_b_0">
			<div class="dflex_wrap">
				<div class="dflex_vertical_c margin_r_40 margin_b_20">
					<div class="search_name">跳转地址：</div>
					<el-input v-model="req.url" placeholder="请输入" class="search_input" @change="search" clearable></el-input>
				</div>
				<div class="dflex_vertical_c margin_r_40 margin_b_20" v-if="advancedSearch">
					<div class="search_name">跳转类型：</div>
					<el-select v-model="req.type" class="search_input" @change="search" clearable>
						<el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
					</el-select>
				</div>
				<div class="dflex_vertical_c margin_r_40 margin_b_20" v-if="advancedSearch">
					<div class="search_name">状态：</div>
					<el-select v-model="req.state" class="search_input" @change="search" clearable>
						<el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
					</el-select>
				</div>
				<el-button size="small" :loading="searchBtnLoading" class="search-btn margin_b_20 margin_r_40" @click="search">搜索</el-button>
				<div class="search_advanced margin_b_20" @click="toggleAdvancedSearch" v-if="!advancedSearch">高级筛选</div>
				<div class="search_common margin_b_20" @click="toggleAdvancedSearch" v-if="advancedSearch">常用筛选</div>
			</div>
		</div>
		<div class="container last_container use-table">
			<div class="dflex_sb margin_b_15 table-head">
				<div>
					<el-button class="batch-btn padding0" :loading="removesBtnLoading" @click="removes">删除<span v-if="selectDatas.length">×{{selectDatas.length}}</span></el-button>
				</div>
				<el-button class="add-btn pos_r padding0" @click="toAdd">
					<el-icon><CirclePlusFilled /></el-icon>新增
				</el-button>
			</div>
			<el-table ref="etbl" :height="tblHeight" v-loading="tableLoading" :data="tableDatas" @selection-change="selectionChange" highlight-current-row>
				<el-table-column type="selection" width="30"></el-table-column>
				<el-table-column label="排序" width="200" align="center">
					<template #default="scope">
						<el-input-number size="small" :min="1" v-model="scope.row.sort" @change="(newSort, oldSort) => sortChange(newSort, oldSort, scope.row)" @blur="scope.row.sort = parseInt(scope.row.sort)"></el-input-number>
					</template>
				</el-table-column>
				<el-table-column label="图片" align="center">
					<template #default="scope">
						<el-image style="width: 120px;height: 40px;padding: 1px;box-sizing: content-box;" :src="scope.row.img" :preview-src-list="scope.row.previewImgs" fit="cover"></el-image>
					</template>
				</el-table-column>
				<el-table-column prop="type" label="跳转类型" align="center"></el-table-column>
				<el-table-column prop="url" label="跳转地址" width="250" align="center"></el-table-column>
				<el-table-column label="状态" align="center">
					<template #default="scope">
						<el-tooltip :open-delay="350" :content="scope.row.state == '启用' ? '点击禁用' : '点击启用'" placement="top" :hide-after="2000" :enterable="false" effect="light">
							<el-switch v-model="scope.row.state" active-color="#ff6a6c" inactive-color="#bbb" active-value="启用" inactive-value="禁用" @change="stateChange(scope.row)"></el-switch>
						</el-tooltip>
					</template>
				</el-table-column>
				<el-table-column label="备注" align="center">
					<template #default="scope">
						<div>{{ scope.row.remark || '--' }}</div>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" fixed="right" width="100">
					<template #default="scope">
						<el-tooltip content="编辑" placement="top" :hide-after="1000" :enterable="false" effect="light">
							<el-button circle class="table-btn" @click="toEdit(scope.row._id)">
								<el-icon><EditPen /></el-icon>
							</el-button>
						</el-tooltip>
						<el-tooltip content="删除" placement="top" :hide-after="1000" :enterable="false" effect="light">
							<el-button circle class="table-btn" @click="remove(scope.row._id)">
								<el-icon><Delete /></el-icon>
							</el-button>
						</el-tooltip>
					</template>
				</el-table-column>
				<el-empty description=" " v-slot:empty></el-empty>
			</el-table>
			<el-pagination background :current-page="req.page" :page-sizes="[10, 20, 30, 50, 100]" :page-size="req.rows" layout="total, sizes, prev, pager, next, jumper" :total="tableTotal" @size-change="sizeChange" @current-change="currentChange"></el-pagination>
		</div>
	</div>
</template>

<script setup>
	const __name = 'usemall-app-carousel'
	import { ref, reactive, onMounted, onUpdated, nextTick, getCurrentInstance } from 'vue'
	import { ElMessageBox, ElMessage } from 'element-plus'

	const { proxy } = getCurrentInstance()
	const advancedSearch = ref(false)
	const tblHeight = ref(0) 
	const tableLoading = ref(false)
	const tableDatas = ref([])
	const tableTotal = ref(0)
	const selectDatas = ref([])
	const searchBtnLoading = ref(false)
	const removesBtnLoading = ref(false)
	const sortLastTime = ref(null)
	const tbl = ref(null)

	const req = reactive({
		page: 1,
		rows: 10,
		orderby: 'sort asc',
		url: '',
		type: '',
		state: ''
	})

	const typeOptions = [
		{ value: '', label: '全部' },
		{ value: '网页', label: '网页' },
		{ value: '页面', label: '页面' }
	]

	const stateOptions = [
		{ value: '', label: '全部' },
		{ value: '启用', label: '启用' },
		{ value: '禁用', label: '禁用' }
	]

	const loadData = async (callback) => {
		tableLoading.value = true

		const res = await proxy.$db[__name]
			.whereif(req.url, {
				url: new RegExp(proxy.$api.filterRegexpKey(req.url), 'i')
			})
			.whereif(req.type, {
				type: req.type
			})
			.whereif(req.state, {
				state: req.state
			})
			.totable(req)
			.then(res => {
				if (res.code == 200) {
					res.datas.rows.forEach((row) => {
						row.previewImgs = [row.img]
					})
			
					tableDatas.value = res.datas.rows
					tableTotal.value = res.datas.total

					if (typeof callback === 'function') {
						callback()
					}
				}
				searchBtnLoading.value = false
				tableLoading.value = false
			})
	}

	const search = () => {
		req.page = 1
		proxy.$api.storagePaginationPage(req.page, proxy.$route.path + '-carousel')
		searchBtnLoading.value = true
		
		loadData(() => {
			proxy.$refs.etbl.bodyWrapper.scrollTop = 0
		})
		
		uni.setStorage({
			key: '__search' + proxy.$route.path + '-carousel',
			data: req
		})
	}

	const toAdd = () => {
		uni.navigateTo({
			url: '/pages/shop/home/carousel_add_edit?tab=添加轮播图',
			events: {
				refreshData: () => {
					loadData()
				}
			}
		})
	}

	const toEdit = (id) => {
		uni.navigateTo({
			url: `/pages/shop/home/carousel_add_edit?id=${id}&tab=编辑轮播图`,
			events: {
				refreshData: () => {
					loadData()
				}
			}
		})
	}
	
	const remove = (id) => {
		ElMessageBox.confirm('此操作将永久删除该数据！', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			proxy.$db[__name].remove(id).then(res => {
				if (res.code == 200) {
					loadData()
				}
			});
		})
	}
	
	const selectionChange = (datas) => {
		selectDatas.value = datas
	}

	const removes = () => {
		if (selectDatas.value.length <= 0) {
			ElMessage.warning('请勾选需要删除的数据！')
			return
		}
		let ids = selectDatas.value.map(x => x._id)
		ElMessageBox.confirm('此操作将永久删除勾选数据！', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			removesBtnLoading.value = true
			
			proxy.$db[__name]
				.where({
					_id: proxy.$db.$cmd.in(ids)
				})
				.remove()
				.then(res => {
					if (res.code == 200) {
						loadData()
					}
					removesBtnLoading.value = false
				}).catch(() => {
					removesBtnLoading.value = false
				})
		})
	}

	const sortChange = (newSort, oldSort, row) => {
		if (!newSort) {
			nextTick(() => {
				row.sort = oldSort
			})
			return
		}
		
		if (event && ['change', 'mouseup'].includes(event.type)) {
			sortUpdate(row)
			return
		}
		
		if (sortLastTime.value !== null) {
			clearTimeout(sortLastTime.value)
		}
		
		sortLastTime.value = setTimeout(() => {
			sortUpdate(row)
		}, 500)
	}

	const sortUpdate  = (row) => {
		proxy.$db[__name].update(row._id, {
			sort: parseInt(row.sort)
		}).catch(() => {
			loadData()
		})
	}

	const stateChange = (row) => {
		proxy.$db[__name].update(row._id, {
			state: row.state
		}).catch(() => {
			loadData()
		})
	}

	const sizeChange = (size) => {
		proxy.$api.storagePaginationRows(size, proxy.$route.path + '-carousel');
		req.page = 1;
		proxy.$api.storagePaginationPage(req.page, proxy.$route.path + '-carousel');
		req.rows = size;
		
		loadData(() => {
			proxy.$refs.etbl.bodyWrapper.scrollTop = 0;
		})
	}

	const currentChange = (current) => {
		proxy.$api.storagePaginationPage(current, proxy.$route.path + '-carousel');
		req.page = current;
		
		loadData(() => {
			proxy.$refs.etbl.bodyWrapper.scrollTop = 0
		})
	}



	const toggleAdvancedSearch = () => {
		advancedSearch.value = !advancedSearch.value
	}

	onMounted(() => {
		let __search = uni.getStorageSync(`__search${proxy.$route.path}-carousel`)
		if (__search) {
			req = __search
			if (req.type || req.state) {
				advancedSearch.value = true
			}
		}
		
		req.page = uni.getStorageSync(`__paginationPage${proxy.$route.path}-carousel`) || 1
		req.rows = uni.getStorageSync(`__paginationRows${proxy.$route.path}-carousel`) || 10
		req.rows = uni.getStorageSync(`__paginationRows${proxy.$route.path}-carousel`) || 10
		
		loadData(() => {
			nextTick(() => {
				proxy.$api.scrollToStorage('.el-table__body-wrapper', `${proxy.$route.path}-carousel`)
			})
		})
		
		nextTick(() => {
			proxy.$api.scrollToStorage('.el-table__body-wrapper', `${proxy.$route.path}-carousel`)
		})
	})

	onUpdated(() => {
		if (!tblHeight.value) {
			tblHeight.value = proxy.$refs.tbl.tblHeight
		}
	})
</script>

<style scoped>
/* 添加样式 */
/* >>> .el-input__wrapper{
	box-shadow: none;
}
>>> .el-input-number__increase:hover~.el-input:not(.is-disabled) .el-input__wrapper{
	box-shadow: none;
} */
</style>
